# ----------------------------------------------------------------------------------------------
# load standard clustermethods pam and kmeans
# - p=pam(x=datapoints vector, k=Number of Clusters), 
#   the resulting clustering is in p$clustering as integer vector
# - p=kmeans(x=datapoints vector, k=Number of Clusters)
#   the resulting clustering is in p$cluster as integer vector
require(cluster)

# ----------------------------------------------------------------------------------------------
# load Chinese Whispers cluster algorithm
# - p=chiWhi(X=datapoints vector, top= next neighbours count)
#   result partition is p
source("chiwhi.R")


#----------------------------------------------------------------------------------------------
# Different strategies to caluclate the params from the datasets dist-matrix and point count n	
kParam<-function(distD,n){ 
	minK=2
	maxK=n^(1/7)*15 
	unique(round(seq(minK,maxK,lenght.out=35)))
}
epsParam <- function(distD,n) {
	minEps=min(distD)
	maxEps=mean(distD)/2
	seq(minEps,maxEps,length.out=35)
}

chiWhiParam <- function(distD,n) {
	minN=5
	maxN=round(sqrt(n)*3)
	unique(round(seq(minN,maxN,length.out=35)))
}

#----------------------------------------------------------------------------------------------
# algos with function to calculate Params
algos<-        list(# KMeans = list(name= "KMeans" , params = kParam ) ,
			  	    PAM    = list(name= "PAM"    , params = kParam)
			  	   , DBScan = list(name= "DBScan" , params = epsParam) 
			  	   , ChiWhi = list(name= "ChiWhi" , params = chiWhiParam)
			  	   )
			  	   
#----------------------------------------------------------------------------------------------
# run given algo with paramsets, returns list of partitions
# 
# runAlgoWithParams(  X :: Matrix , distX :: Matrix, algo :: String, params :: List<Doubles> ) :: indexed list() of partitions
#
runAlgoWithParams<-function(X,distX,algoname,params,MinPts=4) {
	print(paste("--",algoname,params,MinPts))
	partitions <- list(); i = 1;
	for( param in params ) {
		partition <- switch( algoname
			  			   , KMeans = kmeans(X,param)$cluster
			  			   , PAM    = pam(X, param)$clustering
			  			   , DBScan = dbscanCBI(X,param,MinPts)$partition
			  			   , ChiWhi = chiWhi(X,param)
			  			   );
		partitions[[i]] = partition;
		i=i+1;	  			 	
	}
	partitions
}
